package com.easyfun.healthmagicbox.inputviews;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

import com.easyfun.healthmagicbox.R;
import com.easyfun.healthmagicbox.ViewPagerActivity;
import com.easyfun.healthmagicbox.base.BaseActivity;
import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.ormlite.DiseaseTypeEnum;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.pojo.DoctorProfile;
import com.easyfun.healthmagicbox.pojo.DoctorAndHospital;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.GenericRawResults;
import com.j256.ormlite.dao.RawRowMapper;

public class DoctorSearchActivity extends BaseActivity implements DatabaseAccess{
	private static final String[] hospital = { "安贞", "协和", "同仁", "北医三院", "其他" };
	private static final String[] disease = { "糖尿病", "冠心病", "高血压", "中风", "其他" };
	ArrayList<String> allhospitals = new ArrayList<String>();
	private String LOG_TAG = DoctorSearchActivity.class.toString();

	private Spinner spinnerbing;
	private ArrayAdapter<String> bingadapter;
	private Spinner spinnerhos;
	private ArrayAdapter<String> hosadapter;

	private TextView spinnerbingText;
	private TextView spinnerhosText;
	private ArrayList<HashMap<String, Object>> listItem;

	private SimpleAdapter listItemAdapter;

	private int mHosipital = 0;
	private int mDisease = 0;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.doctorsearchlayout);
		// personal ID
		if (!checkPersonId())
			return;

		initalDocSearch();
		
		setupDocoterList();

	}
	
	@Override
	public DatabaseHelper getHelper(Context context) {
		
		return DatabaseAccessImplementation.getInstance().getHelper(context);
	}
	
	ArrayList<String> getAllHospital() {
		
		if (allhospitals.size()==0)
		{
			Dao<DoctorAndHospital, Integer> hospitalDao;
			try {
				hospitalDao = getHelper(this).getHospitalDao();
				List<DoctorAndHospital> hospitals = hospitalDao.queryBuilder()
						.distinct().selectColumns("hospitalName").query();
				for (DoctorAndHospital hos:hospitals)
				{
					allhospitals.add(hos.getHospitalName());
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
			allhospitals.add("Others");
		}
		return allhospitals;

	}
	
	ArrayList<String> getAllDisease() {

		return DiseaseTypeEnum.getAllDisease();

	}

	private void initalDocSearch() {
		spinnerbing = (Spinner) findViewById(R.id.spinnerbing);
		spinnerbingText = (TextView) findViewById(R.id.spinnerbingText);
		// 将可选内容与ArrayAdapter连接起来
		bingadapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, getAllDisease());

		// 设置下拉列表的风格
		bingadapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		// 将adapter 添加到spinner中
		spinnerbing.setAdapter(bingadapter);

		// 添加事件Spinner事件监听
		spinnerbing
				.setOnItemSelectedListener(new deseaseSpinnerSelectedListener());

		// 设置默认值
		spinnerbing.setVisibility(View.VISIBLE);

		spinnerhos = (Spinner) findViewById(R.id.spinnerhos);
		spinnerhosText = (TextView) findViewById(R.id.spinnerhosText);
		// 将可选内容与ArrayAdapter连接起来
		hosadapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, getAllHospital());

		// 设置下拉列表的风格
		hosadapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		// 将adapter 添加到spinner中
		spinnerhos.setAdapter(hosadapter);

		// 添加事件Spinner事件监听
		spinnerhos.setOnItemSelectedListener(new HosSpinnerSelectedListener());

		// 设置默认值
		spinnerhos.setVisibility(View.VISIBLE);
		
	}

	private List<DoctorProfile> searchDoctor()
	{
		List<DoctorProfile> result = new ArrayList<DoctorProfile>();
		try {
			Dao<DoctorProfile, Integer> doctorProfileDao = 
					getHelper(this).getDoctorProfileDao();
			
			List<DoctorProfile> doctors = null;
			if ((!getAllHospital().get(mHosipital).equals("其他"))
				&&(!getAllDisease().get(mDisease).equals("其他")))
			{
				GenericRawResults<DoctorProfile> rawResults =
						doctorProfileDao.queryRaw(
						    "select p.doctorName, p.doctorShortIntro from doctorprofile p, doctorAndDisease d"
						    + " where p.doctorHospital = '"+getAllHospital().get(mHosipital)+"'"
						    + " and d.diseaseName = '"+getAllDisease().get(mDisease)+"'",
						    new RawRowMapper<DoctorProfile>() {
						            public DoctorProfile mapRow(String[] columnNames,
						              String[] resultColumns) {
						                return new DoctorProfile(resultColumns[0],
						                    resultColumns[1]);
						        }
						    });
				doctors = rawResults.getResults();
			}else if(!getAllHospital().get(mHosipital).equals("其他"))
			{

				doctors = doctorProfileDao.queryBuilder()
						.where().eq("doctorHospital",getAllHospital().get(mHosipital))
						   .query();
			}else if(!getAllHospital().get(mHosipital).equals("其他"))
			{

				GenericRawResults<DoctorProfile> rawResults =
						doctorProfileDao.queryRaw(
						    "select p.doctorName, p.doctorShortIntro from doctorprofile p, doctorAndDisease d"
						   
						    + " where d.diseaseName = '"+getAllDisease().get(mDisease)+"'",
						    new RawRowMapper<DoctorProfile>() {
						            public DoctorProfile mapRow(String[] columnNames,
						              String[] resultColumns) {
						                return new DoctorProfile(resultColumns[0],
						                    resultColumns[1]);
						        }
						    });
				doctors = rawResults.getResults();
			}else
			{
				doctors = doctorProfileDao.queryForAll();
			}
			
			for(DoctorProfile doc: doctors)
			{
				
				DoctorProfile dp = new DoctorProfile(doc.getDoctorName(), doc.getDoctorShortIntro());
				
				result.add(dp);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		return result;
		
	}
	
	private void setupDocoterList() {
		// 绑定Layout里面的ListView
		ListView list = (ListView) findViewById(R.id.doctorlist);

		// 生成动态数组，加入数据
		listItem = new ArrayList<HashMap<String, Object>>();
		List<DoctorProfile> docters = searchDoctor();
		for (DoctorProfile docter:docters) {
			HashMap<String, Object> map = new HashMap<String, Object>();

			map.put("ItemTitle", docter.getDoctorName());
			map.put("ItemText", docter.getDoctorShortIntro());
			listItem.add(map);
		}
		
		// 生成适配器的Item和动态数组对应的元素
		listItemAdapter = new SimpleAdapter(this, listItem,// 数据源
				R.layout.medicallistitem,// ListItem的XML实现
				// 动态数组与ImageItem对应的子项
				new String[] { "ItemTitle", "ItemText" },
				// ImageItem的XML文件里面的一个ImageView,两个TextView ID
				new int[] { R.id.ItemTitle, R.id.ItemText });

		// 添加并且显示
		list.setAdapter(listItemAdapter);

		// 添加点击
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

				setTitle("点击第" + arg2 + "个项目");
				new AlertDialog.Builder(DoctorSearchActivity.this)
						.setTitle("显示")
						.setMessage("三金双黄连，每日四次，一次一片")
						.setPositiveButton("是",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										final Intent intent = new Intent(
												DoctorSearchActivity.this,
												ViewPagerActivity.class);
										intent.putExtra(
												ConstantData.HMBPERSONID,
												m_personid);
										DoctorSearchActivity.this
												.startActivity(intent);
									}
								}).show();
			}
		});

	}
	


	class HosSpinnerSelectedListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			mHosipital = position;
			spinnerhosText.setText("你选择的医院是：");
		}

		public void onNothingSelected(AdapterView<?> arg0) {

		}
	}

	class deseaseSpinnerSelectedListener implements OnItemSelectedListener {


		public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			mDisease = position;
			spinnerbingText.setText("你选择的疾病是：");
		}

		public void onNothingSelected(AdapterView<?> arg0) {

		}
	}
}
